<?php

namespace Biz\service\bizActivity\base;

use Doraemon\pockets\constInterface\FormatScene;
use Doraemon\service\Format\Article\HandleArticle;
use Doraemon\service\Format\Note\HandleNote;
use Doraemon\tools\BlockType;
use Doraemon\tools\IdParse;

class ContentService
{
    private $uid = 0;
    private $scene = FormatScene::MASONRY_LAYOUTS;
    private $obj_ids = [];
    private $note_ids = [];
    private $article_ids = [];
    private $unkown_ids = [];
    private $lost_ids = [];
    private $notes = [];
    private $articles = [];
    private $combine = [];
    private $format = null;

    public function __construct($obj_ids = [], $uid = 0, $format = null)
    {
        $this->obj_ids = $obj_ids;
        $this->uid = $uid;
        if ($format) $this->format = $format;
    }

    public function __destruct()
    {
var_dump($this->unkown_ids, $this->lost_ids);
    }

    public function splitContent(): ContentService
    {
        foreach ($this->obj_ids as $obj_id) {
            $type = IdParse::getType($obj_id);
            if ($type == BlockType::TYPE_PHOTO) {
                $this->note_ids[] = $obj_id;
            } elseif ($type == BlockType::TYPE_ARTICLE) {
                $this->article_ids[] = $obj_id;
            } else {
                $this->unkown_ids[$obj_id] = $obj_id;
            }
        }

        if (!empty($this->note_ids)) $this->notes = HandleNote::handleNote($this->note_ids, $this->scene, $this->uid);

        if (!empty($this->article_ids)) $this->articles = HandleArticle::handleArticle($this->article_ids, $this->scene, $this->uid);

        return $this;
    }

    public function combineContent(): ContentService
    {
        foreach ($this->obj_ids as $obj_id) {
            if (isset($this->unkown_ids[$obj_id])) continue;
            if (isset($this->notes[$obj_id])) {
                $this->combine[] = $this->notes[$obj_id];
            } elseif (isset($this->articles[$obj_id])) {
                $this->combine[] = $this->articles[$obj_id];
            } else {
                $this->lost_ids[] = $obj_id;
            }
        }

        return $this;
    }


    public function format()
    {
        return is_callable($this->format) ? call_user_func($this->format, $this->combine) : $this->combine;
    }
}